//@Lim Wei Ke A0083402R
package logic;

import java.util.ArrayList;

import storage.Storage;
import global.CommandType.Type;
import global.Constant;
import global.Task;

public class DeleteCommand extends Command {

	private ArrayList<Integer> indexArray;
	private boolean deleteAll;
	private boolean isExecutable;
	private String feedback;

	public DeleteCommand(ArrayList<Integer> indexArray, boolean deleteAll, boolean isExecutable, String feedback) {
		this.indexArray = indexArray;
		this.deleteAll = deleteAll;
		this.isExecutable = isExecutable;
		this.feedback = feedback;
	}

	public ArrayList<String> execute() {
		ArrayList<String> newFeedback = new ArrayList<String>();
		String illegalFeedback = Constant.EMPTY_STRING;

		if (isExecutable) {
			try {
				ArrayList<Task> tasksDeleted = new ArrayList<Task>();

				if (!deleteAll) {
					int numTasksDeleted = 0;
					for (int i = 0; i < indexArray.size(); i++) {
						int indexToBeDeleted = indexArray.get(i) - 1;

						if (indexToBeDeleted > ExecutionHandler.getDisplayFileNames().size()-1){
							illegalFeedback = ("Illegal index " + (indexToBeDeleted+1) + " entered.\n");
							continue;
						}

						String fileNameToBeDeleted = ExecutionHandler.getDisplayFileNames().get(indexToBeDeleted);
						Task taskToBeDeleted =  Storage.getFileContentAsTask(fileNameToBeDeleted);
						tasksDeleted.add(taskToBeDeleted);

						numTasksDeleted++;
						if (taskToBeDeleted.getTaskType().equalsIgnoreCase(Constant.FLOAT_TASK_TYPE))
							Storage.deleteFileWithoutRecord(fileNameToBeDeleted);
						else
							Storage.deleteFile(fileNameToBeDeleted);
					
					}

					feedback = (numTasksDeleted + " task(s) deleted.\n");
				}
				else {
					for (int i = 0; i < ExecutionHandler.getDisplayFileNames().size(); i++) {
						String fileNameToBeDeleted = ExecutionHandler.getDisplayFileNames().get(i);
						Task taskToBeDeleted =  Storage.getFileContentAsTask(fileNameToBeDeleted);
						tasksDeleted.add(taskToBeDeleted);
						Storage.deleteFile(fileNameToBeDeleted);
					}
					feedback = ("All tasks deleted.\n");
				}

				ExecutionHandler.setMostRecentCommandType(Type.DELETE);
				ExecutionHandler.setOldTasks(tasksDeleted);
				DisplayCommand displayLeft = new DisplayCommand(tasksDeleted);
				newFeedback = displayLeft.displayTasksLeft();
				ExecutionHandler.setIsUndo(false);
			} catch(Exception e){
				feedback = "Deletion Not Successful";
			}
		}

		if (illegalFeedback.isEmpty())
			newFeedback.add(feedback);
		else 
			newFeedback.add(illegalFeedback);

		return newFeedback;
	}
	
	public String getTestFeedback() {
		String testFeedback = "";
		
		if (deleteAll){
			testFeedback = "all";
		} else {
			for (int i=0; i<indexArray.size(); i++){
				testFeedback += (indexArray.get(i)+" ");
			}
		}
		
		return testFeedback;
	}

}
//@Lim Wei Ke A0083402R